package cn.sinocontrol.mqtt.controller;

import cn.sinocontrol.mqtt.pojo.DataSource;
import cn.sinocontrol.mqtt.publish.MqttMsgPublisher;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/mqtt")
public class MqttController {

    private Logger logger = LoggerFactory.getLogger(MqttController.class);

    private MqttMsgPublisher publisher;

    public MqttController(MqttMsgPublisher mqttMsgPublisher) {
        this.publisher = mqttMsgPublisher;
    }

    /**
     * 推送消息
     * @param topic 主题
     * @param payload 消息
     */
    @GetMapping("/publish")
    public void publish(String topic, String payload){
        DataSource dataSource = new DataSource();
        dataSource.source = "CJY-1";
        dataSource.sourceType = "主机卫士";
        dataSource.sourceIP = "192.168.0.192";
        dataSource.eventType = "硬盘:系统盘";
        dataSource.severity = 200;
        dataSource.heartbeat = 1;
        dataSource.time = new Date();
        dataSource.message = payload;
        Gson gson = new GsonBuilder().create();
        String json = gson.toJson(dataSource);

        this.publisher.publishMsg(topic, json);
        logger.info("推送主题-->{},推送消息-->{}", topic, json);
    }
}
